package com.jf.nep.shader;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;

/** Load shader from resource */
public class ShaderLoader {
    public static int loadShader(String url, int type) throws Exception {
        StringBuilder shaderSource = new StringBuilder();
        int shaderID = 0;
        
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(ShaderLoader.class.getResourceAsStream(url)));
            String line;
            while ((line = reader.readLine()) != null) {
                shaderSource.append(line).append("\n");
            }
        } finally {
            if (reader != null) { 
                reader.close();
            }
        }
        
        shaderID = GL20.glCreateShader(type);
        GL20.glShaderSource(shaderID, shaderSource);
        GL20.glCompileShader(shaderID);

        if (GL20.glGetShader(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) {
            String st = GL20.glGetShaderInfoLog(shaderID, 100);
            throw new Exception("Could not compile shader: " + url + " : " + st);
        }
        
        return shaderID;
    }
}
